import { requestGetUserMsg } from '../../request/index.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 商品收藏  店铺名称，店铺图片/食物图片/食物信息/价格/商品id
    choosed: false,
    collectionStoreFood: [],
    food_detail:
    {
      // store_id: 1,
      // food_id: "901",
      // store_img_url: "http://q6zagsjbu.bkt.clouddn.com/1001.jpg",
      // food_name: "香辣鸡腿堡",
      // food_msg: "主要原料:鸡肉",
      // food_pic: "http://q6zagsjbu.bkt.clouddn.com/hamburger.jpg",
      // food_level: 2,
      // storeName: "海哥汉堡",
      // food_sales: 28,
      // food_price: 12,
      // choose_collect: false
    },
    changeCollect: {}
  },
  foodInfo: {},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //1.获取商品id
    let allPage = getCurrentPages();
    // console.log(allPage.length);
    let { food_id } = allPage[allPage.length - 1].options
    // console.log(food_id);
    //2.获取商品详情信息
    this.getFoodDetail(food_id);
    //3.检查是否搜藏该商品
    this.checkCollection();
  },

  handleCarAdd: function () {

    //1.绑定单击  加入购物车  事件
    //2.获取缓存中的购物车数据   数组格式
    let cars = wx.getStorageSync("cars") || [];
    //获取该商品id对应缓存中的索引   不存在index=-1
    let index = cars.findIndex(v => v.food_id === this.data.food_detail.food_id);
    // console.log(cars);
    // console.log(index);
    if (index === -1) {
      //不存在，第一次添加
      this.data.food_detail.num = 1;
      this.data.food_detail.checked = true;
      cars.push(this.data.food_detail);
    } else {
      //存在，执行num+1
      cars[index].num++;
    }
    // 添加完数据后提示添加成功
    wx.setStorageSync("cars", cars);//key  value
    wx.showToast({
      title: '添加成功',
      icon: 'success',
      // mask:true
    })
  },
  // 收藏商品
  async  collect() {

    //判断是否登录
    this.checkLogin();

    //1.获取商品详情信息
    let { food_detail } = this.data;
    // console.log(food_detail.choose_collect)
    // 2.给收藏按钮取反
    food_detail.choose_collect = !food_detail.choose_collect;
    var userInfo = wx.getStorageSync("userInfo");
    // 3.设置回到data中
    this.setData({ food_detail: food_detail, choosed: food_detail.choose_collect })
    // 4.从内存中取出collectionFood   //收藏的集合
    let collectionStoreFood = wx.getStorageSync('collectionStoreFood') || [];
    //4.2 判断 收藏集合是否为空
    if (collectionStoreFood.length > 0) {
      // 根据商品id查询是否存在
      let index = collectionStoreFood.findIndex(v => v.food_id === food_detail.food_id);
      //如果存在替换,不存在添加
      index == -1 ? collectionStoreFood.push({ user_id: collectionStoreFood[0].user_id, store_id: null, food_id: food_detail.food_id }) : collectionStoreFood[index].choose_collect = !collectionStoreFood[index].choose_collect;
    } else {
      //直接添加
      collectionStoreFood.push({ user_id: collectionStoreFood[0].user_id, store_id: null, food_id: food_detail.food_id })
    }
    //5.把收藏商品设置到内存
    wx.setStorageSync('collectionStoreFood', collectionStoreFood);
    // 6.请求服务器 修改改变的信息
    // console.log(food_detail.choose_collect);
    // var json = { user_id: collectionStoreFood[0].user_id, store_id: food_detail.store_id, food_id: food_detail.food_id }
    //根据商品id  电话号码   
    await requestGetUserMsg({ url: "/updateCollectionFoodStore?type=2&phoneNum=" + userInfo.phoneNum, method: "POST", data: { choose_collect: food_detail.choose_collect, food_id: food_detail.food_id } });

  },
  async getFoodDetail(food_id) {
    //根据商品id请求服务器获取数据
    let food_detail = await requestGetUserMsg({ url: "/getFoodDetailByFoodId", data: { food_id: food_id } });
    var fd = food_detail.data[0];
    this.setData({ food_detail: fd })
  },
  async checkCollection() {
    //1.根据用户电话获取收藏的集合
    let userInfo = wx.getStorageSync('userInfo');
    //2.用户存在
    if (userInfo.phoneNum > 1) {
      //3.请求服务器, 获取收藏的店铺的集合   choose_collect  food_detail
      var { data } = await requestGetUserMsg({ url: "/getCollectionStoreFood", data: { phoneNum: userInfo.phoneNum, index: 3 } });
      // console.log(data);
      //4.获取店铺信息
      let food_detail = this.data.food_detail;
      data.forEach(v => v.food_id == food_detail.food_id ? food_detail.choose_collect = true : '');
      this.setData({ food_detail });
      // console.log(data);
      wx.setStorageSync("collectionStoreFood", data);
    } else {
      //2.2用户不存在  啥也不用干
    }
  },
  //立即购买
  handleBuyNow() {
    //0.判断用户是否登录并且绑定手机号
    this.checkLogin();
    //1.添加该商品到购物车
    this.handleCarAdd();
    //2.跳转到支付页面
    wx.navigateTo({ url: '../pay/pay' });
  },
  checkLogin() {
    //0.判断用户是否登录并且绑定手机号
    let userInfo = wx.getStorageSync("userInfo") || [];
    if (userInfo.phoneNum == undefined) {
      wx.navigateTo({
        url: '/pages/my_center/my_center',
        success: (result) => {
          wx.showToast({
            title: '需要登录并且绑定手机号',
            image: '../../icon/jinggao.png',
            duration: 1500
          });
        }
      });
      return;
    }
  }
})